package com.learn.springcloud.zuulreverseproxytzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.io.IOUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

/**
 * @Time : 2018/8/13 16:43
 * @Version : 1.0
 */
@Component
public class QueryParamPostFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        System.out.println("QueryParamPostFilter...");
        RequestContext requestContext = RequestContext.getCurrentContext();
        int responseStatusCode = requestContext.getResponseStatusCode();
        String responseBody = requestContext.getResponseBody();
        System.out.println("responseStatusCode: " + responseStatusCode);
        System.out.println("responseBody: " + responseBody);

        // requestContext.getResponseDataStream() 获取的是 response.getOutputStream中的内容
        try(InputStream responseDataStream = requestContext.getResponseDataStream()){
            if(responseDataStream != null){
                List<String> readlines = IOUtils.readLines(responseDataStream);
                System.out.println("readlines: " + readlines);
                requestContext.setResponseBody(readlines.get(0));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
